local serviceName = "_ama-service"
local displayName = "接收华锐行情后写入DolphinDB流表的本地服务"
local exeName = "ama-service.exe"

-- 服务类定义
Service = {}
Service.__index = Service

-- 构造函数
function Service:new(serviceName, displayName, exePath, workDir)
    local self = setmetatable({}, Service)
    self.serviceName = serviceName
    self.displayName = displayName
    self.exePath = exePath
    self.workDir = workDir
    return self
end

-- 检查服务是否存在
function Service:serviceExists()
    local checkCommand = string.format('sc query "%s"', self.serviceName)
    local handle = io.popen(checkCommand)
    local result = handle:read("*a")
    handle:close()
    return not result:find("1060")
end

-- 安装服务
function Service:install()
  if not self:serviceExists() then
      local installCommand = string.format(
          'nssm install "%s" "%s"',
          self.serviceName, self.exePath
      )
      os.execute(installCommand)

      local setDisplayNameCommand = string.format(
          'nssm set "%s" DisplayName "%s"',
          self.serviceName, self.displayName
      )
      os.execute(setDisplayNameCommand)

      local setWorkDirCommand = string.format(
          'nssm set "%s" AppDirectory "%s"',
          self.serviceName, self.workDir
      )
      os.execute(setWorkDirCommand)

      local setStartTypeCommand = string.format(
          'nssm set "%s" Start "demand"',
          self.serviceName
      )
      os.execute(setStartTypeCommand)

      print("Service installed and configured successfully.")
  else
      print("Service already exists.")
  end
end

-- 卸载服务
function Service:uninstall()
  if self:serviceExists() then
      -- 停止服务
      local stopCommand = string.format('nssm stop "%s"', self.serviceName)
      os.execute(stopCommand)

      -- 删除服务
      local deleteCommand = string.format('nssm remove "%s" confirm', self.serviceName)
      os.execute(deleteCommand)

      print("Service uninstalled successfully.")
  else
      print("Service does not exist.")
  end
  os.exit(0) -- 退出脚本并返回0
end

-- +++++++++++++++++++++++++++++++++++++
--
-- +++++++++++++++++++++++++++++++++++++
-- 获取命令行参数
local args = {...}
local uninstall = false
for _, arg in ipairs(args) do
    if arg == "-u" then
        uninstall = true
        break
    end
end

-- 获取脚本所在目录的绝对路径
local function getScriptPath()
    local p = io.popen("cd"):read("*l")
    return p .. "\\"
end

-- 确定exe文件位置
local workDir = getScriptPath() .. "bin\\"
local exePath = workDir .. exeName

-- 根据命令行参数执行相应的操作
local service = Service:new(serviceName, displayName, exePath, workDir)
if uninstall then
    service:uninstall()
else
    service:install()
end
